import 'dart:async';

import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class MinePage extends StatefulWidget {
   MinePage({super.key, required this.currentIndex});

int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "images/visitor_profile_icon@2x.png",
    }
  ];

  // @override
  // void didUpdateWidget(covariant MinePage oldWidget) {
  //   super.didUpdateWidget(oldWidget);
  //   if (widget.currentIndex == 1) {
  //     // TODO: 调用接口获取数据
  //   }
  // }


Map userInfo = {'avatar': '', 'nickname': '', 'id': ''};

getProfile() async {
  var res = await http.get('/userInfo');
  if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
  // 添加mounted检查，确保组件仍在widget树中
  if (mounted) {
    setState(() {
      userInfo = res['data'];
      print(userInfo);
    });
  }
}

@override
void didUpdateWidget(covariant MinePage oldWidget) {
  super.didUpdateWidget(oldWidget);
  if (widget.currentIndex == 1) {
    getProfile();
  }
}

// @override
// void initState() {
//   super.initState();
//    eventBus.on<RefreshMine>().listen((event) {
//       getProfile();
//     });
// }

// 添加一个变量来保存订阅
StreamSubscription? _subscription;

@override
void initState() {
  super.initState();
  _subscription = eventBus.on<RefreshMine>().listen((event) {
    getProfile();
  });
}

@override
void dispose() {
  // 取消订阅
  _subscription?.cancel();
  super.dispose();
}



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/profile', arguments: userInfo);
              },
              child: Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(50.0),
                    child: userInfo['avatar'] != null && userInfo['avatar'] != '' 
                      ? Image.network(
                          userInfo['avatar'],
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover,
                        )
                      : Image.asset(
                          'images/avatar_1.jpg',
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover,
                        )
                  ),
                  const SizedBox(width: 10),
                  Text(
                    userInfo['nickName'] != null && userInfo['nickName'] != '' 
                      ? userInfo['nickName'] 
                      : '用户名',
                    style: const TextStyle(fontSize: 16, color: Colors.white)
                  ),
                  const Spacer(),
                  const Text(
                    '去完善信息',
                    style: TextStyle(color: Colors.white),
                  ),
                  const Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.white,
                    size: 13,
                  )
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: [
                ...menuList
                  .map(
                    (item) => SizedBox(
                      height: 50,
                      child: Row(
                        children: [
                          Row(
                            children: [
                              Image.asset(
                                item['icon'],
                                width: 20,
                                height: 20,
                              ),
                              const SizedBox(
                                width: 10,
                              ),
                              Text(
                                item['title'],
                                style: const TextStyle(fontSize: 16),
                              )
                            ],
                          ),
                          const Spacer(),
                          const Icon(
                            Icons.arrow_forward_ios,
                            size: 12,
                            color: Colors.grey,
                          )
                        ],
                      ),
                    ),
                  )
                  .toList(),

                  // 测试代码， 测试token 的操作
                  ElevatedButton(
                    onPressed: () {
                      TokenManager().saveToken('test token~');
                    },
                    child: const Text('存储token'),
                  ),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      TokenManager().removeToken();
                    },
                    child: const Text('删除token'),
                  ),
              ],
            ),
          )
        ],
      ),
    );
  }
}